package com.wx.controller;

import com.wx.service.SleuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class SleuthController {

    private static final Logger logger = LoggerFactory.getLogger(SleuthController.class);

    @Autowired
    private SleuthService sleuthService;

    @GetMapping("/span")
    public String helloSleuthSameSpan() {
        logger.info("Same Span");
        sleuthService.doSomeWorkSameSpan();
        return "success";
    }

    @GetMapping("/asyncSpan")
    public String helloSleuthAsync() {
        logger.info("Before Async Method Call");
        sleuthService.asyncMethod();
        logger.info("After Async Method Call");
        return "success";
    }

    @GetMapping(value = "feture")
    public String feture() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        // Kick of multiple, asynchronous lookups
        CompletableFuture<String> page1 = sleuthService.sendUser("1");
        CompletableFuture<String> page2 = sleuthService.sendUser("2");
        CompletableFuture<String> page3 = sleuthService.sendUser("3");

        // Wait until they are all done
        // join() 的作用：让“主线程”等待“子线程”结束之后才能继续运行
        CompletableFuture.allOf(page1,page2,page3).join();

        // Print results, including elapsed time
        float exc = (float)(System.currentTimeMillis() - start)/1000;
        logger.info("Elapsed time: " + exc + " seconds");
        logger.info("--> " + page1.get());
        logger.info("--> " + page2.get());
        logger.info("--> " + page3.get());
        return "feture";
    }
}
